package com.baibei.product.trade;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.baibei.basic.BaibeiBasicDialogFragment;
import com.baibei.model.CouponInfo;
import com.baibei.model.ProductInfo;
import com.baibei.model.RankingInfo;
import com.baibei.model.TradeParams;
import com.baibei.model.TradeType;
import com.baibei.module.AppRouter;
import com.baibei.module.RechargeHelper;
import com.baibei.module.UserStatus;
import com.baibei.product.R;
import com.baibei.product.R2;
import com.baibei.ui.AppUI;
import com.baibei.widget.BaibeiNumberBar;
import com.baibei.widget.dialog.TradeDialog;
import com.rae.swift.Rx;
import com.rae.widget.dialog.DialogBuilder;
import com.rae.widget.dialog.IAppDialog;
import com.rae.widget.dialog.IAppDialogClickListener;
import com.suke.widget.SwitchButton;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.content.ContentValues.TAG;

/**
 * 订购交易
 * Created by ChenRui on 2017/8/7 0007 14:56.
 */
public class TradeFragment extends BaibeiBasicDialogFragment implements TradeContract.View {

    @BindView(R2.id.tv_use_coupon_count)
    TextView mTvUseCouponCount;
    @BindView(R2.id.switch_button)
    SwitchButton mSwitchButton;
    private TradeContract.Presenter mPresenter;
    private TextWatcher mTextWatcher;
    private List<CouponInfo> mCouponInfos;
    private List<Integer> mSuggestNumbers;
    private int mMaxCount;
    private Context mContext;
    private double close;

    public static TradeFragment newInstance(ProductInfo product, TradeType type, List<CouponInfo> infos, List<Integer> numbers, int maxDefindCount) {
        Bundle args = new Bundle();
        args.putParcelable("productInfo", product);
        args.putString("type", type.name());
        args.putParcelableArrayList("coupons", (ArrayList<? extends Parcelable>) infos);
        args.putIntegerArrayList("suggest", (ArrayList<Integer>) numbers);
        args.putInt("maxCount", maxDefindCount);
        TradeFragment fragment = new TradeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    private TradeType mType;

    @BindView(R2.id.tv_dialog_title)
    TextView mTitleView;

    @BindView(R2.id.btn_price_customer)
    EditText mCustomerQuantityText;

    @BindView(R2.id.btn_ensure)
    Button mEnSureView;

    @BindView(R2.id.nb_up)
    BaibeiNumberBar mUpBar;

    @BindView(R2.id.nb_down)
    BaibeiNumberBar mDownBar;

    @BindView(R2.id.tv_amount)
    TextView mAmountView;

    @BindView(R2.id.tv_fee)
    TextView mFeeView;

    @BindView(R2.id.tv_use_ticket)
    TextView mTvUseTicket;

    private final TradeParams mParams = new TradeParams();

    private TradeConfirmFragment mConfirmFragment;

    // 快速选择价格
    private List<Button> mQuickQuantityList = new ArrayList<>();
    private int mCurrentItem;
    private ProductInfo mProductInfo;
    private CouponInfo mHasSuitable;
    /**
     * 监听事件
     */
    private OnTradeSuccessListener mOnListener;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new TradeDialog(getContext());
    }

    @Override
    protected void onBindView(View view) {
        ButterKnife.bind(this, view);
    }

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.widget_dialog_trade;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mProductInfo = getArguments().getParcelable("productInfo");
        mType = TradeType.valueOf(getArguments().getString("type", TradeType.BUY.name()));
        mCouponInfos = getArguments().getParcelableArrayList("coupons");
        mSuggestNumbers = getArguments().getIntegerArrayList("suggest");
        mMaxCount = getArguments().getInt("maxCount", 1000);
        if (mProductInfo == null) {
            getActivity().finish();
            return;
        }

        mPresenter = inject(TradeContract.Presenter.class);


        mConfirmFragment = TradeConfirmFragment.newInstance(mParams);
        mConfirmFragment.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                if (mConfirmFragment.isEnsure()) {
                    IAppDialog loading = AppUI.loading(getContext(), "订货中，请稍后..", 0.6f);
                    loading.setCanceledOnTouchOutside(false);
                    loading.setOnCancelListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            mPresenter.cancel();
                            mEnSureView.setEnabled(true);
                        }
                    });
                    mEnSureView.setEnabled(false);
                    mPresenter.trade();
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.resume();
    }

    @OnClick(R2.id.img_close)
    public void onCloseClick() {
        dismiss();
    }

    /**
     * 交易
     */
    @OnClick(R2.id.btn_ensure)
    public void onEnSureClick() {
        mParams.type = mType;
        mParams.quantity = getQuantity();
        mParams.upPercent = mUpBar.getValue();
        mParams.downPercent = mDownBar.getValue();
        mParams.productId = Rx.parseInt(mProductInfo.getProductId());
        mParams.close = close;

        //#382 java.lang.IllegalStateException
        //This happens when we try to add same fragment or DialogFragment twice before dismissing,
        if (!mConfirmFragment.isAdded()) {
            mConfirmFragment.show(getFragmentManager(), mParams);
        }
        Log.e(TAG, "onEnSureClick: "+mProductInfo.getClosePrice() );
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mPresenter.destroy();
        mQuickQuantityList.clear();
        mCustomerQuantityText.removeTextChangedListener(mTextWatcher);
        mQuickQuantityList = null;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mQuickQuantityList.add((Button) view.findViewById(R.id.btn_price10));
        mQuickQuantityList.add((Button) view.findViewById(R.id.btn_price50));
        mQuickQuantityList.add((Button) view.findViewById(R.id.btn_price100));
        mQuickQuantityList.add((Button) view.findViewById(R.id.btn_price200));
        mQuickQuantityList.add((Button) view.findViewById(R.id.btn_price500));

        //数量一致，才进行赋值
        if (mQuickQuantityList.size() == mSuggestNumbers.size()) {
            for (int i = 0; i < mQuickQuantityList.size(); i++) {
                Button button = mQuickQuantityList.get(i);
                button.setText(String.valueOf(mSuggestNumbers.get(i)));
            }
        }
        mQuickQuantityList.get(0).setSelected(true);
        //记录默认的体验券使用
        mSwitchButton.setOnCheckedChangeListener(mOnCheckedChangeListener);
        onPriceClick(mQuickQuantityList.get(0));

        mTitleView.setText(mType == TradeType.BUY ? getString(R.string.title_trade_buy) : getString(R.string.title_trade_sell));

        // 结算价订货
        if (mType == TradeType.SELL) {
            mEnSureView.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.sellColor));
        }

        mTextWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                int value = Rx.parseInt(charSequence.toString());
                mCustomerQuantityText.removeTextChangedListener(mTextWatcher);
                if (value > mMaxCount) {
                    mCustomerQuantityText.setText(mMaxCount + "");
                    value = mMaxCount;
                    mCustomerQuantityText.setSelection(mCustomerQuantityText.length());
                } else if (value <= 0 && !TextUtils.isEmpty(charSequence)) {
                    mCustomerQuantityText.setText("1");
                    value = 1;
                    mCustomerQuantityText.setSelection(mCustomerQuantityText.length());
                }
                onCustomerPriceChanged();
                mCustomerQuantityText.addTextChangedListener(mTextWatcher);

                //bug---当不选择的时候，会默认使用上一个选择的数量，使用体验券
                isCouponValiable(value);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        };

        //限制最大值
        mCustomerQuantityText.addTextChangedListener(mTextWatcher);
//        CashierInputFilter cashierInputFilter = new CashierInputFilter();
//        cashierInputFilter.setMaxValue(1000);
//        InputFilter[] inputFilter = {cashierInputFilter};
//        mCustomerQuantityText.setFilters(inputFilter);

        //添加可用券标识
        addCouponFlag();

        mPresenter.getClosePrice();
    }

    /**
     * 添加体验券标识
     */
    private void addCouponFlag() {
        for (CouponInfo couponInfo : mCouponInfos) {
            for (Button button : mQuickQuantityList) {
                //如果有相应面值，显示flag
//                if (true){
                if (couponInfo.getFaceValue() == Rx.parseInt(button.getText())) {
                    ImageView flag = new ImageView(getContext());
                    flag.setImageResource(R.mipmap.icon_has_coupon);
                    FrameLayout layout = (FrameLayout) button.getParent();
                    FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
                    lp.bottomMargin = 40;
                    lp.gravity = Gravity.RIGHT | Gravity.TOP;
                    flag.setLayoutParams(lp);
                    layout.addView(flag);
                }
            }
        }
    }

    /**
     * 加载产品信息
     */
    private void onLoadProductInfo(ProductInfo productInfo) {

    }

    public void onCustomerPriceChanged() {
        if (TextUtils.isEmpty(mCustomerQuantityText.getText())) {
            setCurrentItem(mCurrentItem); // 默认选择
        } else {
            setCurrentItem(-1);
        }

        // 计算价格
        calc();
    }

    @OnClick({R2.id.btn_price10,
            R2.id.btn_price50,
            R2.id.btn_price100,
            R2.id.btn_price200,
            R2.id.btn_price500})
    public void onPriceClick(View view) {
        mCustomerQuantityText.setText("");
        int size = mQuickQuantityList.size();
        for (int i = 0; i < size; i++) {
            Button button = mQuickQuantityList.get(i);
            button.setSelected(button == view);
            if (button == view) {
                mCurrentItem = i;
                isCouponValiable(Rx.parseInt(button.getText()));
            }
        }

        // 计算价格
        calc();
    }


    /**
     * 根据体验券，是否可用
     * 数量
     *
     * @param count count
     */
    private void isCouponValiable(int count) {
        mHasSuitable = null;
        mSwitchButton.setChecked(false);
        for (CouponInfo couponInfo : mCouponInfos) {
            if (couponInfo.getFaceValue() == count) {
                mHasSuitable = couponInfo;
            }
        }
        mSwitchButton.setEnabled(mHasSuitable != null);
        if (mHasSuitable != null) {
            mTvUseCouponCount.setText(String.format(getString(R.string.valiable_ticket_count), mHasSuitable.getFaceValue()));
        } else {
            mTvUseCouponCount.setText(R.string.no_valiable_ticket);
        }
    }

    /**
     * 是否选择
     * 记录参数
     */
    private SwitchButton.OnCheckedChangeListener mOnCheckedChangeListener = new SwitchButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(SwitchButton switchButton, boolean checked) {
            if (checked) {
                mParams.couponInfo = mHasSuitable;
                //订货服务费
                mFeeView.setText(Rx.formatPrice(0));
                mAmountView.setText(Rx.formatPrice(0));
                mTvUseTicket.setVisibility(View.VISIBLE);
            } else {
                mParams.couponInfo = null;
                mTvUseTicket.setVisibility(View.GONE);
                mFeeView.setText(Rx.formatPrice(mParams.fee));
                mAmountView.setText(Rx.formatPrice(mParams.amount));
            }
        }
    };


    /**
     * 找到当前选择的项目
     */
    protected int getCurrentItem() {
        int size = mQuickQuantityList.size();
        for (int i = 0; i < size; i++) {
            if (mQuickQuantityList.get(i).isSelected())
                return i;
        }
        return -1;
    }

    /**
     * 取消所有的选择状态
     */
    protected void setCurrentItem(int position) {
        if (position >= 0) {
            mCurrentItem = position;
        }
        int size = mQuickQuantityList.size();
        for (int i = 0; i < size; i++) {
            mQuickQuantityList.get(i).setSelected(i == position && position >= 0);
        }
    }

    /**
     * 获取价格
     */
    protected int getQuantity() {
        int position = getCurrentItem();
        CharSequence text;
        if (position >= 0) {
            text = mQuickQuantityList.get(position).getText();
        } else {
            text = mCustomerQuantityText.getText();
        }
        return Rx.parseInt(text);
    }

    public ProductInfo getProduct() {
        return mProductInfo;
    }

    /**
     * 计算价格已经订货服务费
     */
    public void calc() {
        int quantity = getQuantity();
        double amount = mProductInfo.getPrice() * quantity; // 订金
        double fee = mProductInfo.getFee() * quantity; //订货服务费
        mParams.amount = amount;
        mParams.fee = fee;
        mAmountView.setText(Rx.formatPrice(amount));
        mFeeView.setText(Rx.formatPrice(fee));
    }

    @Override
    public TradeParams getTradeParams() {
        return mParams;
    }

    @Override
    public ProductInfo getProductInfo() {
        return mProductInfo;
    }

    @Override
    public void onTradeFailed(String msg) {
        mEnSureView.setEnabled(true);
        AppUI.dismiss();
        AppUI.failed(getContext(), mTitleView.getText() + "订货失败，" + msg);
        dismiss();
    }

    @Override
    public void onTradeSuccess(String msg) {
        //回调上层
        if (mOnListener != null) {
            mOnListener.onTradeSuccess();
        }
        mEnSureView.setEnabled(true);
        AppUI.dismiss();
        AppUI.success(getContext(), msg);
        dismiss();
    }

    @Override
    public void onTradeTimeout() {
        AppUI.dismiss();
        new DialogBuilder(getContext())
                .setMessage(mTitleView.getText() + "超时，请勿重复下单，是否现在前往订单中心？")
                .setCancelable(false)
                .setCanceledOnTouchOutside(false)
                .negativeButtonText("暂不")
                .positiveButtonText("立即前往")
                .negativeButtonClickListener(new IAppDialogClickListener() {
                    @Override
                    public void onClick(IAppDialog dialog, int i) {
                        dialog.dismiss();
                        dismiss();
                    }
                })
                .positiveButtonClickListener(new IAppDialogClickListener() {
                    @Override
                    public void onClick(IAppDialog dialog, int i) {
                        dialog.dismiss();
                        AppRouter.routeToOrderCenter(getActivity());
                        getActivity().finish();
                        dismiss();
                    }
                })
                .show();
    }

    @Override
    public void onTradeExist() {
        AppUI.dismiss();
        new DialogBuilder(getContext())
                .setMessage("需先退订该品种后，才能再次预定")
                .setCancelable(false)
                .setCanceledOnTouchOutside(false)
                .negativeButtonHidden()
                .positiveButtonText("我知道了")
                .positiveButtonClickListener(new IAppDialogClickListener() {
                    @Override
                    public void onClick(IAppDialog dialog, int i) {
                        dialog.dismiss();
                        dismiss();
                    }
                })
                .show();
    }

    @Override
    public void onAttach(Activity context) {
        super.onAttach(context);
        mContext = context;
    }


    @Override
    public void onNotMoney() {
        dismiss();
        AppUI.dismiss();
        mEnSureView.setEnabled(true);
        new DialogBuilder(getContext())
                .setMessage("账户可用余额不足，前往充值？")
                .positiveButtonClickListener(new IAppDialogClickListener() {
                    @Override
                    public void onClick(IAppDialog dialog, int i) {
                        dialog.dismiss();
                        RechargeHelper.toRecharge((Activity) mContext, (UserStatus) mContext);
//                        dismiss();
                    }
                })
                .show();
    }

    @Override
    public void onGetRankingInfoSuccess(List<RankingInfo> rankingInfos) {
        Log.e(TAG, "onGetRankingInfoSuccess: "+mProductInfo.getProductId() );
        String productId = mProductInfo.getProductId();
        for (RankingInfo rankingInfo : rankingInfos){
            if (rankingInfo.getProductId().equals(productId)){
                close = rankingInfo.getClose();
            }
        }
    }


    /**
     * call back
     */
    interface OnTradeSuccessListener {

        /**
         * 交易成功
         */
        void onTradeSuccess();
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnTradeSuccessListener) {
            mOnListener = (OnTradeSuccessListener) context;
        }
    }
}
